package mutilthread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description: 阻塞队列实现生产者消费者模型
 * User: Li_yizYa
 * Date: 2025—03—31
 * Time: 20:37
 */
public class Demo16 {
    public static void main(String[] args) {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue(1000);

        //生产者线程
        Thread t1 = new Thread(() -> {
            int i = 1;
            while (true) {
                try {
                    queue.put(i);
                    System.out.println("生产元素 " + i);
                    i++;

                    //给生产操作，加上 sleep， 生产慢点，消费快点
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        //消费者线程
        Thread t2 = new Thread(() -> {
            while (true) {
                try {
                    Integer i = queue.take();
                    System.out.println("消费元素 " + i);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        t1.start();
        t2.start();
    }
}
